﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using Tunnel.Tools;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Windows.Forms;

namespace Tunnel.Plan
{
    /// <summary>
    /// 本类型定义了定时运行预案的后台服务
    /// </summary>
    public class TimeToRun
    {
        /// <summary>
        /// 预案定时器
        /// </summary>
        public System.Timers.Timer timer = new System.Timers.Timer(60000);
        List<(int, int, string)> timeList = new List<(int, int, string)>();
        /// <summary>
        /// 构造方法，获取定时列表，初始化定时器
        /// </summary>
        public TimeToRun()
        {
            GetTimeList();
            timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            //bwRunPlan.DoWork += BwRunPlan_DoWork;
            
        }
        /// <summary>
        /// 重新启动定时预案
        /// </summary>
        public void RestartTimer()
        {
            GetTimeList();
            timer.Start();
        }
        /// <summary>
        /// 启动定时预案触发器
        /// </summary>
        public void StartTimer()
        {
            timer.Start();
        }
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime currentTime = DateTime.Now;
            int currentHour = currentTime.Hour;
            int currentMinute = currentTime.Minute;

            foreach(var (h,m, planID) in timeList)
            {
                if((currentHour==h)&&(currentMinute==m))
                {
                    BackgroundWorker bwRunPlan = new BackgroundWorker();
                    bwRunPlan.WorkerReportsProgress = true;
                    bwRunPlan.DoWork += new DoWorkEventHandler(TimeToRunPlan);
                    //bwRunPlan.ProgressChanged += BwRunPlan_ProgressChanged;
                    bwRunPlan.RunWorkerCompleted += BwRunPlan_RunWorkerCompleted;
                    bwRunPlan.RunWorkerAsync(planID);                    
                }
            }
        }

        private void BwRunPlan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.Append("已于\r\n");
            stringBuilder.Append(DateTime.Now.ToLongTimeString());
            stringBuilder.Append("\r\n下发定时预案指令");
            MessageBox.Show(stringBuilder.ToString(), "预案自动下发");
        }

        private void BwRunPlan_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
        }

        public void TimeToRunPlan(object sender, DoWorkEventArgs e)
        {
            string planID = e.Argument as string;
            BackgroundWorker worker = sender as BackgroundWorker;
            DBHelper dh = new DBHelper();
            string sql = "SELECT M_PlanInfo.PlanInfoID, M_PlanInfo.PlanID, M_PlanInfo.DeviceID, M_PlanInfo.PlanInfo, M_PlanInfo.PlanPlayList, M_PlanInfo.Number, M_Device.Name, M_Device.TypeID FROM M_PlanInfo LEFT OUTER JOIN M_Device ON M_PlanInfo.DeviceID = M_Device.DeviceID WHERE (M_PlanInfo.PlanID = @id)";
            SqlCommand sqlCommand = new SqlCommand(sql);
            sqlCommand.Parameters.Add(new SqlParameter("@id", planID));
            DataTable dtPlanTime = dh.GetTable(sqlCommand);
            List<(string, string, string, string, string)> planInfoElements = new List<(string, string, string, string, string)>();
            foreach (DataRow dr in dtPlanTime.Rows)
            {
                //PlanInfoElement planInfoElement = new PlanInfoElement();
                string deviceName = string.Empty;
                string deviceStatus = dr["PlanInfo"].ToString();
                string deviceID = dr["DeviceID"].ToString();
                string deviceTypeID = string.Empty;
                if (!string.IsNullOrEmpty(dr["TypeID"].ToString()))
                {
                    deviceTypeID = dr["TypeID"].ToString();
                }
                else
                {
                    if (deviceID.Contains("Light"))
                    {
                        deviceTypeID = "Light";
                    }
                }
                string devicePlayListID = string.Empty;
                if (!string.IsNullOrEmpty(dr["PlanPlayList"].ToString()))
                {
                    devicePlayListID = dr["PlanPlayList"].ToString();
                }
                planInfoElements.Add((deviceName, deviceStatus, deviceID, deviceTypeID, devicePlayListID));
            }
            //Console.WriteLine("");
            DataDeal.RunPlan(planInfoElements, worker);            
        }

        private void GetTimeList()
        {
            DBHelper dh = new DBHelper();
            string getTimeListString = "SELECT M_TimePlan.TimePlanID,M_TimePlan.Hour,M_TimePlan.Minute,M_TimePlan.PlanID,M_Plan.PlanName,M_Plan.PlanText FROM M_TimePlan LEFT OUTER JOIN M_Plan ON M_TimePlan.PlanID = M_Plan.PlanID ORDER BY Hour,Minute";
            DataTable timePlan = dh.GetTable(getTimeListString);
            timeList.Clear();
            foreach (DataRow row in timePlan.Rows)
            {
                timeList.Add((int.Parse(row["Hour"].ToString()), int.Parse(row["Minute"].ToString()), row["PlanID"].ToString()));
            }
        }
    }
}
